package pers.xhh.frontapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xhh.frontapi.common.Mi;
import pers.xhh.frontapi.common.ResultCode;
import pers.xhh.frontapi.dao.MiCategoryDao;
import pers.xhh.frontapi.entity.MiCategoryEntity;
import pers.xhh.frontapi.entity.MiGoodsEntity;
import pers.xhh.frontapi.entity.MiGoodsPicsEntity;
import pers.xhh.frontapi.entity.to.goods.MiGoodsTo;
import pers.xhh.frontapi.entity.vo.banner.Banner;
import pers.xhh.frontapi.entity.vo.category.MiCategoryVo;
import pers.xhh.frontapi.entity.vo.goods.MiGoodsVo;
import pers.xhh.frontapi.service.MiCategoryService;
import pers.xhh.frontapi.service.MiGoodsAttrService;
import pers.xhh.frontapi.service.MiGoodsPicsService;
import pers.xhh.frontapi.service.MiGoodsService;
import pers.xhh.frontapi.util.DateUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiCategoryServiceImpl extends ServiceImpl<MiCategoryDao, MiCategoryEntity> implements MiCategoryService {

    @Autowired
    MiGoodsService miGoodsService;

    @Autowired
    MiGoodsAttrService miGoodsAttrService;

    @Autowired
    MiGoodsPicsService miGoodsPicsService;

    @Override
    public Mi listCategory(Integer type, Integer pagenum, Integer pagesize) {
        // ->如果pagenum和pagesize有一个为空,不分页
        if (pagenum == null || pagesize == null) {
            if(type != null){
                // 如果type为1
                if (type == 1) {
                    List<MiCategoryVo> collect = getMiCategoryByType(type);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
                }
                if (type == 2) {
                    List<MiCategoryVo> collect = getMiCategoryByType(type);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
                }
                if (type == 3) {
                    List<MiCategoryVo> collect = getMiCategoryByType(type);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
                }
            }
        }
        // ->分页条件都不为空
        if (pagenum != null && pagesize != null) {
            // 分页条件不为空,由于children的限制,只能查询出全部在分页,否则children也
            // TODO 后期可优化
            List<MiCategoryVo> collect = getMiCategoryByType(3);
            // 先对cat_level进行分页
            List<MiCategoryVo> list = new ArrayList<>();
            int total = collect.size();
            // 从哪开始
            int start = (pagenum - 1) * pagesize;
            // 截多少 pagesize
            int j = 0;
            for (int i = start; i < collect.size(); i++) {
                j++;
                list.add(collect.get(i));
                if(j == pagesize){
                    break;
                }
            }

            Map<String, Object> map = new HashMap<>();
            map.put("result", list);
            map.put("total", total);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }

        // ->默认全部,参数给错也一样
        List<MiCategoryVo> collect = getMiCategoryByType(3);
        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);

    }

    @Override
    public Mi getCateOneList() {

        List<MiCategoryEntity> categoryEntities = this.list(new QueryWrapper<MiCategoryEntity>().eq("cat_pid", 0));

        List<Map<String, Object>> collect = categoryEntities.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("catOneId", item.getCatId());
            map.put("catOneName", item.getCatName());
            // ->分页 固定10条
            Page<MiGoodsEntity> page = new Page<>(1, 10);
            QueryWrapper<MiGoodsEntity> queryWrapper =
                    new QueryWrapper<MiGoodsEntity>().eq("cat_one_id", item.getCatId());
            miGoodsService.page(page, queryWrapper);

            // —>结果
            List<MiGoodsEntity> records = page.getRecords();
            Map<String, Object> goodsMap = new HashMap<>();
            System.out.println(records.size());
            if (records.size() > 0) {
                List<MiGoodsVo> miGoodsVos = records.stream().map(miGoodsEntity -> {
                    MiGoodsVo miGoodsVo = new MiGoodsVo();
                    miGoodsVo.setCat_id(miGoodsEntity.getCatId());
                    miGoodsVo.setCat_one_id(miGoodsEntity.getCatOneId());
                    miGoodsVo.setCat_two_id(miGoodsEntity.getCatTwoId());
                    miGoodsVo.setCat_three_id(miGoodsEntity.getCatThreeId());
                    miGoodsVo.setGoods_id(miGoodsEntity.getGoodsId());
                    miGoodsVo.setGoods_name(miGoodsEntity.getGoodsName());
                    miGoodsVo.setGoods_number(miGoodsEntity.getGoodsNumber());
                    miGoodsVo.setGoods_price(miGoodsEntity.getGoodsPrice());
                    miGoodsVo.setGoods_weight(miGoodsEntity.getGoodsWeight());
                    miGoodsVo.setGoods_state(miGoodsEntity.getGoodsState());
                    miGoodsVo.setIs_promote(miGoodsEntity.getIsPromote() == 1);
                    miGoodsVo.setAdd_time(DateUtils.formatDate(miGoodsEntity.getCreateTime()));
                    // 查询pics
                    List<MiGoodsPicsEntity> miGoodsPicsEntityList =
                            miGoodsPicsService.list(new QueryWrapper<MiGoodsPicsEntity>().eq("goods_id", miGoodsEntity.getGoodsId()));
                    if(miGoodsPicsEntityList != null && miGoodsPicsEntityList.size() > 0){
                        List<MiGoodsTo.Pics> picsList = miGoodsPicsEntityList.stream().map(picsEntity -> {
                            MiGoodsTo.Pics pics = new MiGoodsTo.Pics();
                            pics.setPic(picsEntity.getPicsBig());
                            return pics;
                        }).collect(Collectors.toList());
                        miGoodsVo.setPics(picsList);
                    }

                    return miGoodsVo;
                }).collect(Collectors.toList());
                long total = page.getTotal();
                long current = page.getCurrent();

                goodsMap.put("goods", miGoodsVos);
                goodsMap.put("total", total);
                goodsMap.put("pagenum", current);
            }
            map.put("list", goodsMap);

            return map;
        }).collect(Collectors.toList());
        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
    }

    @Override
    public Mi getBanner() {
        Banner banner1 = new Banner();
        banner1.setId(1);
        banner1.setImgPath("1.jpg");

        Banner banner2 = new Banner();
        banner1.setId(2);
        banner1.setImgPath("2.jpg");

        Banner banner3 = new Banner();
        banner1.setId(3);
        banner1.setImgPath("3.jpg");

        List<Banner> banners = new ArrayList<>();
        banners.add(banner1);
        banners.add(banner2);
        banners.add(banner3);

        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), banners);
    }

    private List<MiCategoryVo> getMiCategoryByType(Integer type) {
        QueryWrapper<MiCategoryEntity> queryWrapper = new QueryWrapper<>();
        if (type == 1) {
            queryWrapper =
                    new QueryWrapper<MiCategoryEntity>().eq("cat_level", type - 1);
        }
        if (type == 2) {
            queryWrapper =
                    new QueryWrapper<MiCategoryEntity>()
                            .eq("cat_level", type - 2)
                            .or()
                            .eq("cat_level", type - 1);
        }
        if (type == 3) {
            queryWrapper = new QueryWrapper<>();
        }
        // TODO 修改为逻辑删除 cat_deleted：0未删除;1删除 添加这个条件
        List<MiCategoryEntity> catLevel = this.list(queryWrapper);
        List<MiCategoryVo> miCategoryVos = catLevel.stream().map(item -> {
            MiCategoryVo miCategoryVo = new MiCategoryVo();
            miCategoryVo.setCat_id(item.getCatId());
            miCategoryVo.setCat_name(item.getCatName());
            miCategoryVo.setCat_pid(item.getCatPid());
            miCategoryVo.setCat_level(item.getCatLevel());
            miCategoryVo.setCat_deleted(item.getCatDeleted() == 1);
            return miCategoryVo;
        }).collect(Collectors.toList());

        // 找到一级菜单,递归查询
        return miCategoryVos.stream().filter(miCategoryVo ->
                miCategoryVo.getCat_level() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, miCategoryVos, type));
            return menu;
        }).collect(Collectors.toList());
    }

    // 找到一级菜单下的子菜单,递归查找菜单的所有子菜单
    private List<MiCategoryVo> getChildren(MiCategoryVo root, List<MiCategoryVo> all, Integer type) {
        List<MiCategoryVo> collect = all.stream().filter(categoryVo ->
                categoryVo.getCat_pid().equals(root.getCat_id())
        )
                .map((menu) -> {
                    // 找到子菜单
                    if(type == 2){
                        if(menu.getCat_level() <= 0){
                            menu.setChildren(getChildren(menu, all, type));
                        }
                    } else {
                        if(menu.getCat_level() <= 1){
                            menu.setChildren(getChildren(menu, all, type));
                        }
                    }
                    return menu;
                }).collect(Collectors.toList());

        return collect;
    }

}
